package common.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import play.Logger;

import common.facebook.FBConstants;
import common.util.Util;

/**
 * <pre>
 * HTTP 요청에 대한 처리를 담당하는 클래스
 * 2012.05.14 : 신규등록 (박상헌)
 * </pre>
 * @author 박상헌
 *
 */
public class HTTPRequest {
	
	/**
	 * <pre>
	 * URL 과 Parameter를 이용하여 HTTP 요청을 하고 그에 대한 응답을 byte배열로 받는다.
	 * 2012.05.14 : 신규등록 (박상헌)
	 * </pre>
	 * @param url
	 * @param params
	 * @return
	 */
	public static byte[] getResponse(String remoteURL, Map<String, String> params) {
		byte[] readData = null;
		String requestURL = null;
		
		if (params != null) {
			String queryString = Util.createQueryString(params);
			requestURL = remoteURL + queryString;
		} else {
			requestURL = remoteURL;
		} // if
		
		Logger.debug("REQUEST URL : " + requestURL);
		
		try {
			URL url = new URL(requestURL);
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
			
			int resCode = conn.getResponseCode();
			String resMsg = conn.getResponseMessage();
			Logger.debug("Response Code : " + resCode);
			Logger.debug("Response Message : " + resMsg);
			
			Logger.debug("Content Length : " + conn.getContentLength());
			Logger.debug("Content Name : " + conn.getContent().getClass().getName());
			InputStream in = conn.getInputStream();
			
			byte[] buffer = new byte[conn.getContentLength()];
			ByteBuffer readBuffer = ByteBuffer.allocate(conn.getContentLength() * 2);
			int totalRead = 0;
			while(true) {
				int read = in.read(buffer);
				if (read < 0) break;
				readBuffer.put(buffer);
				totalRead += read;
			} // while
			Logger.debug("Total Read : " + totalRead);
			
			readData = readBuffer.array();
		} catch (MalformedURLException e) {
			Logger.error(e.getMessage());
		} catch (IOException e) {
			Logger.error(e.getMessage());
		}
		
		return readData;
	} // getResponse
} // class HTTPRequest
